import { fileURLToPath, URL } from 'node:url'

import { defineConfig, loadEnv } from 'vite'
import UnoCSS from 'unocss/vite'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import VueDevTools from 'vite-plugin-vue-devtools'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import mockDevServerPlugin from 'vite-plugin-mock-dev-server'
import path from 'node:path'
import basicSsl from '@vitejs/plugin-basic-ssl'

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  // Load env file based on `mode` in the current working directory.
  // Set the third parameter to '' to load all env regardless of the `VITE_` prefix.
  const env = loadEnv(mode, process.cwd(), '')
  return {
    plugins: [
      UnoCSS(),
      //https://github.com/pengzhanbo/vite-plugin-mock-dev-server/blob/main/README.zh-CN.md
      env.VITE_USE_MOCK === 'true' &&
        mockDevServerPlugin({
          prefix: [`^${env.VITE_BASE_API}`], //默认与server.proxy一致，并且如果server.proxy的ws配置与http配置相同时，会失效。
          wsPrefix: [`^${env.VITE_BASE_WS}`], //ws不会与server.proxy一致
          include: ['mock/**/*.mock.{js,ts,cjs,mjs,json,json5}'], //配置读取 mock文件，可以是一个 目录，glob，或者一个数组
          exclude: ['**/node_modules/**', '**/.vscode/**', '**/.git/**'],
          reload: false, //true：mock资源更新后会刷新页面
          cors: true,
          log: 'info',
          formidableOptions: {
            uploadDir: path.join(process.cwd(), 'uploads')
          },
          cookiesOptions: {},
          build: false //需要构建可独立部署的小型mock服务时配置。
        }),
      vue(),
      AutoImport({
        include: [
          /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
          /\.vue$/,
          /\.vue\?vue/, // .vue
          /\.md$/ // .md
        ],
        resolvers: [ElementPlusResolver()],
        imports: [
          'vue',
          'vue-router',
          // {
          //     'axios': [
          //         // default imports
          //         ['default', 'axios'], // import { default as axios } from 'axios',
          //     ],
          // },
          {
            from: '@vueuse/core',
            imports: ['useClipboard'],
            type: false
          },
          // example type import
          {
            from: 'vue-router',
            imports: ['RouteRecordRaw'],
            type: true
          },
          {
            from: 'element-plus',
            imports: ['ElMessageBox', 'ElMessage'],
            type: false
          }
        ],
        // global imports to register
        eslintrc: { enabled: true }
      }),
      Components({
        // allow auto load markdown components under `./src/components/`
        extensions: ['vue', 'md'],
        // allow auto import and register components used in markdown
        include: [/\.vue$/, /\.vue\?vue/, /\.md$/],
        resolvers: [ElementPlusResolver()],
        dts: 'components.d.ts'
      }),
      VueDevTools(),
      /*使用@vitejs/plugin-basic-ssl插件生成ssl证书，https访问，具体见server.https*/
      env.VITE_USE_SSL === 'true' && basicSsl({
        /** name of certification */
        name: 'test',
        /** 自定义域名*.custom.com */
        domains: ['localhost'],
        /** custom certification directory */
        certDir: '/Users/.../.devServer/cert'
      })
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },
    server: {
      host: true,
      port: JSON.parse(env.VITE_PORT),
      open: env.VITE_OPEN === 'true',
      hmr: true,
      proxy: {
        [`^${env.VITE_BASE_API}`]: {
          target: env.VITE_API_URL,
          changeOrigin: true,
          rewrite: (path: string) => path.replace(new RegExp(`^${env.VITE_BASE_API}`), '')
        },
        //代理ws路径
        [`^${env.VITE_BASE_WS}`]: {
          target: env.VITE_WS_URL,
          ws: true
        }
      }
    }
  }
})
